<template>
    <div>
        <div class="main-head flex-between container-fluid">
            <div class="title">
                <h1 v-text="$t('pro.rules.Rules')"></h1>
            </div>
        </div>
        <div class="content container-fluid">
            <div class="portlet">
                <div class="tools flex-between">
                    <div class="grid">
                        <a-button type="primary" @click="CreateRules" style="margin-right: 10px;" v-text="$t('pro.rules.CreateRules')" />
                        <a-input-search :placeholder="$t('pro.campaigns.searchPlaceholder')" @search="onSearch"/>
                    </div>
                </div>
                <div class="table">
                    <template v-if="empty">
                        <a-empty image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original">
                            <span slot="description">{{$t('pro.rules.emptyRules')}}</span>
                        </a-empty>
                    </template>
                    <template v-else>
                        <a-table
                                :pagination="false"
                                :columns="columns"
                                :loading="loading"
                                rowKey="id"
                                @change="handleTableChange"
                                :dataSource="data"
                                :scroll="{x: '1200px'}"
                        >
                            <template
                                    slot="name"
                                    slot-scope="text, record"
                            >
                                <a style=" margin: 0 auto;
                                           width: 150px;
                                           overflow:hidden;
                                           white-space:nowrap;
                                           text-overflow:ellipsis;
                                           display: block"
                                   @click="handleEditRules(record)"
                                >
                                    {{record.name}}
                                </a>
                            </template>
                            <span slot="Type" slot-scope="text">
                                {{handleTypeFormat(text)}}
                            </span>
                            <span slot="Ordinal" slot-scope="text">
                                {{handleOrdinalFormat(text)}}
                            </span>
                            <span slot="Oper" slot-scope="text">
                                {{text?text:"-"}}
                            </span>
                            <a slot="action"  slot-scope="text,record" href="javascript:;" style="max-width: 155px;display: flex;justify-content:space-around">
                                <a-button
                                        :title="$t('pro.rules.CopyRules')"
                                        type="primary"
                                        shape="circle"
                                        icon="copy"
                                        @click="handleCopy(text)"
                                        style="margin-right: 5px;"
                                />
                                <a-button
                                        :title="$t('pro.rules.DelRules')"
                                        type="primary"
                                        shape="circle"
                                        icon="delete"
                                        @click="handleDelRules(record)"
                                        style="margin-right: 5px;"
                                />
                            </a>
                        </a-table>
                    </template>

                    <a-pagination
                        v-if="!empty"
                        style="text-align: right;margin-top:1rem;"
                        showSizeChanger
                        showQuickJumper
                        :pageSizeOptions="pageSizeOptions"
                        :pageSize="pagination.size"
                        :total="pagination.total"
                        v-model="pagination.current"
                        @showSizeChange="handleChange"
                        @change="handleChange"
                    >
                    </a-pagination>
                </div>

                <!--复制自定义规则的模态框-->
                <a-modal
                        :title="$t('pro.campaigns.DupModelOK')"
                        v-model="visibleDup"
                        @ok="handleCopyRules"
                        :okText="$t('pro.campaigns.DupModelOK')"
                        :cancelText="$t('pro.public.buttonClose')"
                        :confirmLoading="confirming"
                        @cancel="handleCopyClose"
                >
                    <a-table
                            rowKey="name"
                            size="small"
                            :pagination=false
                            bordered
                            :columns="Duplicatecolumns"
                            :dataSource="DuplicateData"
                    >
                        <span slot="name" v-text="DuplicateData[0].name"></span>
                        <a-input type="textarea" slot="newname" v-model="newName">
                        </a-input>
                    </a-table>
                </a-modal>
            </div>
        </div>
    </div>
</template>

<script>
    import {getAllRuleData,getCopyRule,getDelRule} from "@/api/rule-controller";
    import {parseTime} from '@/utils/time'
    export default {
        data(){
            return {
                data: [],
                //screenWidth: document.body.clientWidth,
                confirming:false,
                DuplicateData: [{name: ""}],
                copyRulesId: null,
                newName: '',
                visibleDup: false,
                loading: false,
                empty: false, //判断是否有数据
                pagination: {
                    size: 10,
                    current: 1,
                    total:10
                }, //分页器
                pageSizeOptions: ['10','20','30'],  //分页下拉列表
            }
        },
        computed:{
            Duplicatecolumns(){
                return this.$t('pro.rules.Duplicatecolumns')
            },
            columns() {
                return this.$t('pro.rules.columns')
            },// 用户rules的所有数据列
            operandTypeArr(){
                return this.$t('pro.EditRules.operandType')
            },
            operandOrdinalArr(){
                return this.$t('pro.EditRules.operandOrdinal')
            },
        },
        methods:{
            //处理操作类型的显示函数
            handleTypeFormat(text){
                if (text !== undefined){
                    let textType
                    this.operandTypeArr.forEach(item =>{
                        if (text == item.key){
                            textType = item.name
                        }
                    })
                    return textType
                } else {
                    return "-"
                }

            },

            handleOrdinalFormat(text){
                if (text !== undefined){
                    let textOrdinal
                    this.operandOrdinalArr.forEach(item =>{
                        if (text == item.key){
                            textOrdinal = item.name
                        }
                    })
                    return textOrdinal
                } else {
                    return "-"
                }

            },

            /*resize(){
                this.screenWidth = document.body.clientWidth;
            },*/

            //表格的发生改变的刷新事件
            handleTableChange(pagination, filters, sorter) {
                this.pagination = pagination;
                this.fetch({
                    sortField: sorter.field,
                    sortOrder: sorter.order,
                    ...filters
                });
            },

            //查询回写
            fetch(params = {}) {
                this.loading = true;
                params.page = this.pagination.current || 1
                params.results = this.pagination.size || 10
                getAllRuleData({...params})
                    .then(res => {
                        const { data } = res.data;
                        if (data.length == 0) {
                            this.empty = true
                        } else {
                            this.data = [];
                            this.data = data.records.map(item => {
                                item.updatedAt = parseTime(item.updatedAt)
                                return item
                            })
                            this.pagination = data //每页
                        }
                    }).finally(() => {
                        this.loading = false
                    });
            },
            //跳转到创建规则界面
            CreateRules(){
                this.$router.push({
                    path: '/admin/editRules',
                })
            },
            //改变页数的事件
            handleChange(page, pageSize) {
                this.pagination.size = pageSize
                this.pagination.current = page
                this.fetch()
            },
            // 复制广告活动
            handleCopy(text) {
                this.visibleDup = true
                let name = text.name;
                if (this.DuplicateData.length == 1) {
                    this.DuplicateData[0]['name'] = name
                }
                this.newName = name + '-Copy'
                this.copyRulesId = text.id
            },
            //确认复制自定义规则
            handleCopyRules() {
                this.confirming = !this.confirming;//开启按钮等待动画
                getCopyRule({
                    id: this.copyRulesId,
                    copyName: this.newName
                }).then(res => {
                    if (res.data.code == 200) {
                        this.$message.success(this.$t('pro.campaigns.DuplicateSuccess'));
                    }

                }).catch(err => {
                    this.$message.error(this.$t('pro.campaigns.DuplicateError'));

                }).finally(()=>{
                    this.getVisible()
                    this.visibleDup = false
                })
            },
            getVisible() {//复制操作结束后的关闭模态框和关闭按钮动画
                this.confirming = !this.confirming;//关闭按钮等待动画
                this.fetch();
            },
            //关闭复制广告活动模态框的事件
            handleCopyClose() {
                this.visibleDup = false
            },
            //模糊查询
            onSearch(value){
                this.fetch({vague: value})
            },
            //删除自定义规则
            handleDelRules(record) {
                let that = this
                this.$confirm({
                    title: this.$t('pro.rules.DelRulesTitle'),
                    content:this.$t('pro.rules.DelRulesContent'),
                    okText: this.$t('pro.public.buttonYes'),
                    okType: "danger",
                    cancelText: this.$t('pro.public.buttonNo'),
                    onOk() {
                        that.loading = true
                        getDelRule({
                            "ids":[record.id]
                        })
                            .then(res => {
                                if (res.data.data){//如果删除成功
                                    that.$message.success(that.$t('pro.filterList.delete_Success'));
                                    that.fetch()
                                }
                            })
                            .catch(err => {
                                if (err){
                                    that.$message.error(that.$t('pro.filterList.delete_Error'));
                                }
                            })
                    },
                    onCancel() {},
                });
            },
            //编辑自定义规则
            handleEditRules(record){
                this.$router.push({
                    path: `/admin/editRules/id/` + record.id
                })
            },
        },
        watch:{
        },
        mounted(){
            this.fetch();
        }
    }
</script>

<style scoped>
    .grid {
        grid-template-columns: repeat(5, auto);
    }
</style>
